// Если поле obj пустое - заполняет его подсказкой из аттрибута placeholder
/*function fieldHint(obj, type) {
        var ph = obj.getAttribute('placeholder');
        if (obj.value && obj.value != ph) {return;}
        obj.value = type ? '' : ph;
       
        obj.style.color = type ? $(obj).removeClass("inactive") : $(obj).addClass("inactive") ;
    }*/
    
function PresentAct(present, // "моё" желание (если mode='abandon', то это желание, кот. "Я" предложил осуществить)
                    user,    // юзер, предложивший осуществить моё желание (если mode='abandon', то это юзер, которому "Я" предложил осуществить желание)
                    mode
                    ) {
    if(!IsInteger(present) || !IsInteger(user) || (mode!='approve' && mode!='deny' && mode!='confirm' && mode!='delete') && mode!='abandon') return false;

    var fRet; 
    if(mode == 'deny') {
        fRet = confirm(lang_confirm_delete_offer);    
        if(!fRet) return false;    
    }
    
    if(mode == 'delete') {
        fRet = confirm(lang_confirm_reject_offer);    
        if(!fRet) return false;    
    }
    
    if(mode == 'abandon') current_user = user; 
        
    $.ajax({
    url: current_location + '/' + index_script,         
    data: "id=" + current_user + "&" + place_name + "=presents_ajax&" + mode_name + "=" + mode + "&prid=" + present + '&user=' + user + "&ajax=yes",
    type: 'POST',
    dataType: 'html',
    success: function (result){
        if(result == 'OK') {
            if(mode == 'approve' || mode == 'confirm') {
                $('#user_' + user).html(lang_moder_approved);
                $('#user_' + user).css("color", "green");
            } else if(mode == 'abandon') {                
                $('.link_btn').closest('p').css("color", "green");       
                $('.link_btn').closest('p').html(lang_moder_my_cancelled); 
            } else {
                $('#user_' + user).html(lang_moder_cancelled);
                $('#user_' + user).css("color", "gray");
            }
            //alert(result); 
           // $('.give_btn').unbind('click').addClass('gived').html(lang_gived);
        }
        else {
            if(mode == 'abandon') {
                $('.link_btn').closest('p').css("color", "red");
                $('.link_btn').closest('p').html(lang_error);                
            } else {
                $('#user_' + user).html(lang_error);
                $('#user_' + user).css("color", "red"); 
            }
           // $('.give_btn').unbind('click').addClass('error').html(lang_error);
        }
    },
    error: function (xhr, ajaxOptions, thrownError){
        $('.give_btn').unbind('click').addClass('error').html(lang_error);
    }
    });
}    
 
function pre_delete(user, id) {
    var fRet; 
    fRet = confirm(lang_confirm_delete_present); 
    if(fRet) window.location.href = current_location + '/' + index_script + '?id=' + user + '&' + place_name + '=presents&' + mode_name + '=delete&prid=' + id ;
}

// Проверяет является ли строка целочисленным выражением
function IsInteger(strString)
   {
   var strValidChars = "0123456789";
   var strChar;
   var blnResult = true;

   if (strString.length == 0 || strString.length > 10) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }

function give(present, need) {
    var count = typeof($('.give_form input#give_count').val()) == 'undefined' ? 1 : $('.give_form input').val();
    
    if(!IsInteger(count)) {
        alert(lang_wrong_data);
        return;
    }
    
    if(count > need) {
        alert(lang_too_many_presents);
        return;
    }
        
    $.ajax({
        url: current_location + '/' + index_script,
        data: "id=" + current_user + "&" + place_name + "=presents_ajax&" + mode_name + "=give&prid=" + present + '&prcount=' + count + "&ajax=yes",
        type: 'POST',
        dataType: 'html',
        success: function (result){
            if(result == 'OK') 
                $('.give_btn').unbind('click').addClass('gived').html(lang_gived);
            else 
                $('.give_btn').unbind('click').addClass('error').html(lang_error);
        },
        error: function (xhr, ajaxOptions, thrownError){
            $('.give_btn').unbind('click').addClass('error').html(lang_error);
        }
        });
        
    $('.give_form').fadeOut(); 
    $(".msg_bg").hide(); 
}    
    
function show_present(id_ /* "юзер_желание" */) {
        var id_list = id_.split('_');     
        if(id_list.length != 2 || !IsInteger(id_list[0]) || !IsInteger(id_list[1])) return false;
        
        var userid = id_list[0]
        var prid = id_list[1];     
        id = '#' + id_;    
    
        $(id).addClass("active").siblings("li").removeClass("active").css("background-color", "");
        var bcol = $(id).css("background-color");
        $(id).animate({ backgroundColor: "white" }, "fast").animate({ backgroundColor: bcol }, "fast");  
        
        $.ajax({
            url: current_location + '/' + index_script,
            data: "id=" + /*current_user*/ userid + "&" + place_name + "=presents_ajax&" + mode_name + "=view&prid=" + prid + "&ajax=yes",
            type: 'POST',
            dataType: 'html',
            success: function (result){  
                        $('.present_desc').html(result);
                        if(/*can_edit*/loggedin_user==userid) {
                            
                            general_use();
                            
                        /*    $("#calendar").datepicker({ changeMonth: true, changeYear: true}); // календарь
                            tinyMCE.init({                                                                              // редактор
                                mode : "textareas", 
                                theme : "simple" 
                            }); */
                            // подсказки в инсертах
                            $('input[title!=""]').hint();
                            $('#edit_btn').click(function(){ $("#p_view").hide(); $("#p_edit").fadeIn(); }); 
                            $('#info_btn').click(function(){ $('.desc_info').slideToggle("fast"); $(this).toggleClass("active");}); 
                            
                    /*        // ---- Форма -----
                            var options = {
                            //beforeSubmit: showRequest,
                            //target: '#err_ajax',
                            resetForm: false,
                            clearForm: false,
                            success: function (responseText, statusText) {      
                                if(IsInteger(responseText)) {   
                                    window.location.href = current_location + '/' + index_script + '?id=' + current_user + '&' + place_name + '=presents&' + mode_name + '=' + mode + '&prid=' + responseText;  
                                  //  return false;
                                }
                                else {
                                    $('#err_ajax').html(responseText);
                                    $(".msg_close").click( function(){ $(this).closest('div').fadeOut(); $(".msg_bg").hide();} ); 
                                }
                            },
                            error: function (xhr, ajaxOptions, thrownError) { alert('error: ' + thrownError); }
                            };
                             $('#present_form').ajaxForm(options);
                            // ---- Форма -----     */
                        } else {
                            // нажатие кнопки "Подарить"
                            $('.give_btn:not(.error)').click(function(){ $('.msg_bg').fadeIn('fast'); $('.give_form').fadeIn(); });
                            $(".msg_close").click( function(){ $(this).closest('div').fadeOut(); $(".msg_bg").hide();} ); 
                        }
                        // всплывающие подсказки
                        $('form input, #btn, span').tooltip({
                            track: true,
                            delay: 0,
                            showURL: false,
                            showBody: " - ",
                            fade: 150
                        }); 
                        $(".present_desc").addClass("active").show();
                        if(typeof(bcol) != 'undefined') $(".present_desc").animate({ backgroundColor: "white" }, "fast").animate({ backgroundColor: bcol }, "fast");
                        $('#desc').fadeIn();
                        
                        // обновление "ссылки для копирования" на страницу
                        $('.wish_link').val(current_location + '/' + /*current_user*/ userid + '/' + prid);
                        
                        
            },
            error: function (xhr, ajaxOptions, thrownError){
                $('.present_desc').hide();
                $('.present_desc').html("<center><b>ERROR</b><br>" + xhr.status + "<br>" + thrownError + "</center>").fadeIn();
            }   
            });   
} 
                                                         
/*********************** UPLOAD ********************************/
 //create a preview of the selection
function preview(img, selection) { 
    //get width and height of the uploaded image.
    var current_width = $('#uploaded_image').find('#thumbnail').width();
    var current_height = $('#uploaded_image').find('#thumbnail').height();

    var scaleX = thumb_width / selection.width; 
    var scaleY = thumb_height / selection.height; 
    
    $('#uploaded_image').find('#thumbnail_preview').css({ 
        width: Math.round(scaleX * current_width) + 'px', 
        height: Math.round(scaleY * current_height) + 'px',
        marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px', 
        marginTop: '-' + Math.round(scaleY * selection.y1) + 'px' 
    });
    $('#x1').val(selection.x1);
    $('#y1').val(selection.y1);
    $('#x2').val(selection.x2);
    $('#y2').val(selection.y2);
    $('#w').val(selection.width);
    $('#h').val(selection.height);
} 

//show and hide the loading message
function loadingmessage(msg, show_hide){
    if(show_hide=="show"){
        $('#loader').show();
        $('#progress').show().text(msg);
        $('#uploaded_image').html('');
    }else if(show_hide=="hide"){
        $('#loader').hide();
        $('#progress').text('').hide();
    }else{
        $('#loader').hide();
        $('#progress').text('').hide();
        $('#uploaded_image').html('');
    }
}

//delete the image when the delete link is clicked.
function deleteimage(large_image, thumbnail_image){
    loadingmessage(lang_deleting_images, 'show');
    $.ajax({
        type: 'POST',
        url: image_handling_file,
        data: 'a=delete&large_image='+large_image+'&thumbnail_image='+thumbnail_image,
        cache: false,
        success: function(response){
            loadingmessage('', 'hide');
            response = unescape(response);
            var response = response.split("|");
            var responseType = response[0];
            var responseMsg = response[1];
            if(responseType=="success"){
              //  $('#upload_status').show().html('<h1>Success</h1><p>'+responseMsg+'</p>');
                $('#uploaded_image').html('');
                $('#uploaded_img').val('');
                $('#uploaded_img_url').val('');
                $('#del_img_button').hide();
                $('#select_image').show();
                $('#select_image_btns').show();
                $('#input_img_url').val('');
            }else{
                $('#upload_status').show().html(lang_unexpected_error+response);
            }
        }
    });
}

// удаление сохраненного изображения (файл на сервере и запись в БД)
function deleteimage_saved(delid, what){               
    var what_id = "";
    if(what=="avatar") {what_id = "userid"}
    else if(what=="pr_image") {what_id = "prid"}
    else return;
    
    loadingmessage(lang_deleting_images, 'show');
    $.ajax({
        type: 'POST',
        url: current_location + '/' + index_script,
        data: "id=" + current_user + "&" + place_name + "=images&" + mode_name + "=delete_" + what + "&" + what_id + "=" + delid + "&ajax=yes",
        cache: false,
        success: function(response){           
            loadingmessage('', 'hide');
            response = unescape(response);
            var response = response.split("|");
            var responseType = response[0];
            var responseMsg = response[1];
            if(responseType=="success"){
              //  $('#upload_status').show().html('<h1>Success</h1><p>'+responseMsg+'</p>');
                $('#uploaded_image').html('');
                $('#uploaded_img').val('');
                $('#uploaded_img_url').val('');
                $('#del_img_button').hide();
                $('#img_saved').hide();
                $('#img_new').show();
                if(what=="avatar") $('.user_info img').attr('src', skin_images_dir + '/user.png');
         //       $('#select_image').show();
         //       $('#select_image_btns').show();
            }else{
                $('#upload_status').show().html(lang_unexpected_error+response);
            }
        }
    });
}



            
            
function select_from_url(v){
    if (v.length == 0) return false; 
    
    loadingmessage(lang_copying_images, 'show');    
    $.ajax({
        type: 'POST',
        url: image_handling_file,
        data: {upload:'Upload', url: v}, //'a=delete&large_image='+large_image+'&thumbnail_image='+thumbnail_image,
        cache: false,
        success: function(response){
            loadingmessage('', 'hide');
            response = unescape(response);
            var response = response.split("|");
            var responseType = response[0];
            var responseMsg = response[1];
            if(responseType=="success"){
                
                // иконка
                var thmb_path = response[4];
                var thmb_width = response[5];
                var thmb_height = response[6];
                    
                //put the image in the appropriate div without thumb
                $('#uploaded_image').html('<img src="'+current_location+ '/' +responseMsg+'" id="thumbnail"  />');
                $('#uploaded_img').val(responseMsg);
                $('#uploaded_thumb').val(thmb_path);
                $('#del_img_button').click(function() {deleteimage(responseMsg, thmb_path); }).show();
                $('#select_image').hide();
            }else{
                $('#upload_status').show().html(lang_unexpected_error+response);

            }
        }
    });
}
/*********************** UPLOAD ********************************/ 

function general_use() {

// ---- календарь
        //$("#calendar").datepicker({ changeMonth: true, changeYear: true}); 
        
// ---- редактор    
   /*     tinyMCE.init({                                                     
            mode : "textareas", 
            theme : "simple" 
        });     */
        
       // var my_ne = new nicEditor({iconsPath : scripts_dir + '/nicedit/nicEditorIcons.gif', buttonList : ['bold','italic','underline','strikeThrough','left','center','right','justify','ol','ul','hr','forecolor','bgcolor','removeformat']}).panelInstance('description');
                     
// ---- Форма -----
        var options = {
        resetForm: false,
        clearForm: false,
        success: function (responseText, statusText) {    
            if($('#ajax_form').attr('name') == 'new_present_form' && IsInteger(responseText)) {
                // редирект на добавленное желание
                window.location.href = current_location + '/' + index_script + '?id=' + current_user + '&' + place_name + '=presents&' + mode_name + '=' + mode + '&prid=' + responseText;  
            }
            else if($('#ajax_form').attr('name') == 'settings_form') {
                // редирект на страницу настроек
                $('#err_ajax').html(responseText);
                $(".msg_close").click( function(){ $(this).closest('div').fadeOut(); $(".msg_bg").hide(); window.location.href = current_location + '/settings';} );
            }
            else {
                $('#err_ajax').html(responseText);
                $(".msg_close").click( function(){ $(this).closest('div').fadeOut(); $(".msg_bg").hide();} ); 
            }
        },
        error: function (xhr, ajaxOptions, thrownError) { alert('error: ' + thrownError); }
        };
         $('#ajax_form').ajaxForm(options);
// ---- Форма -----  
        
// ---- UPLOAD IMAGE --->>
        $('#loader').hide();
        $('#progress').hide();
        var myUpload = $('#upload_link').upload({
           name: 'image',
           action: image_handling_file,
           enctype: 'multipart/form-data',
           params: {upload:'Upload'},
           autoSubmit: true,
           onSubmit: function() {
                   $('#upload_status').html('').hide();
                loadingmessage(lang_uploading_images, 'show');      
           },
           onComplete: function(response) {   
                   loadingmessage('', 'hide');
                response = unescape(response);
                var response = response.split("|");
                var responseType = response[0];
                var responseMsg = response[1];  
                if(responseType=="success"){      
                    var current_width = response[2];
                    var current_height = response[3];
                    
                    // иконка
                    var thmb_path = response[4];
                    var thmb_width = response[5];
                    var thmb_height = response[6];
                    
                    //display message that the file has been uploaded
                  //  $('#upload_status').show().html('<h1>Success</h1><p>The image has been uploaded</p>');
                    //если нужно сделать иконку
                    if(create_thumb) {
                        //put the image in the appropriate div
                        $('#uploaded_image').html('<img src="'+current_location+ '/' +responseMsg+'" id="thumbnail" alt="Create Thumbnail" /><div style="border:1px #e5e5e5 solid; float:left; position:relative; overflow:hidden; width:'+thumb_width+'px; height:'+thumb_height+'px;"><img src="'+responseMsg+'" style="position: relative;" id="thumbnail_preview" alt="Thumbnail Preview" /></div>');                        
                        //find the image inserted above, and allow it to be cropped
                        $('#uploaded_image').find('#thumbnail').imgAreaSelect({ aspectRatio: '1:'+thumb_height/thumb_width, onSelectChange: preview }); 
                        //display the hidden form
                        $('#thumbnail_form').show();
                    } else {
                        //put the image in the appropriate div without thumb
                        $('#uploaded_image').html('<img src="'+current_location+ '/' +responseMsg+'" id="thumbnail" />');
                        $('#uploaded_img').val(responseMsg);
                        $('#uploaded_thumb').val(thmb_path);
                        $('#del_img_button').click(function() {deleteimage(responseMsg, thmb_path); }).show();
                        $('#select_image').hide();
                    }
                }else if(responseType=="error"){ 
                    switch (responseMsg) {
                        case '1': responseMsg = lang_image_error1; break;
                        case '2': responseMsg = lang_image_error2; break;
                        case '3': responseMsg = lang_image_error3; break;
                        case '4': responseMsg = lang_image_error4; break;
                    }
                    $('#upload_status').show().html('<h1>'+lang_error+'</h1><p>'+responseMsg+'</p>');
                    $('#uploaded_image').html('');
                    $('#uploaded_img').val('');
                    $('#thumbnail_form').hide();
                    $('#del_img_button').hide(); 
                }else{
                    $('#upload_status').show().html(lang_unexpected_error+response);
                    $('#uploaded_image').html('');
                    $('#uploaded_img').val('');  
                    $('#thumbnail_form').hide();
                    $('#del_img_button').hide();
                //    loadingmessage('Error!', 'show'); 
                }
           }
        });
    
    //create the thumbnail
 /*   $('#save_thumb').click(function() {
        var x1 = $('#x1').val();
        var y1 = $('#y1').val();
        var x2 = $('#x2').val();
        var y2 = $('#y2').val();
        var w = $('#w').val();
        var h = $('#h').val();
        if(x1=="" || y1=="" || x2=="" || y2=="" || w=="" || h==""){
            alert("You must make a selection first");
            return false;
        }else{
            //hide the selection and disable the imgareaselect plugin
            $('#uploaded_image').find('#thumbnail').imgAreaSelect({ disable: true, hide: true }); 
            loadingmessage('Please wait, saving thumbnail....', 'show');
            $.ajax({
                type: 'POST',
                url: image_handling_file,
                data: 'save_thumb=Save Thumbnail&x1='+x1+'&y1='+y1+'&x2='+x2+'&y2='+y2+'&w='+w+'&h='+h,
                cache: false,
                success: function(response){
                    loadingmessage('', 'hide');
                    response = unescape(response);
                    var response = response.split("|");
                    var responseType = response[0];
                    var responseLargeImage = response[1];
                    var responseThumbImage = response[2];
                    if(responseType=="success"){
                        $('#upload_status').show().html('<h1>Success</h1><p>The thumbnail has been saved!</p>');
                        //load the new images
                        $('#uploaded_image').html('<img src="'+responseLargeImage+'" alt="Large Image"/>&nbsp;<img src="'+responseThumbImage+'" alt="Thumbnail Image"/><br /><a href="javascript:deleteimage(\''+responseLargeImage+'\', \''+responseThumbImage+'\');">Delete Images</a>');
                        //hide the thumbnail form
                        $('#thumbnail_form').hide();
                    }else{
                        $('#upload_status').show().html('<h1>Unexpected Error</h1><p>Please try again</p>'+response);
                        //reactivate the imgareaselect plugin to allow another attempt.
                        $('#uploaded_image').find('#thumbnail').imgAreaSelect({ aspectRatio: '1:'+thumb_height/thumb_width, onSelectChange: preview }); 
                        $('#thumbnail_form').show();
                    }
                }
            });
            
            return false;
        }
    });    */
    
    
// <<--- UPLOAD IMAGE ----        
}


$(document).ready(function(){
  
    $("#loading").bind("ajaxSend", function(){
        $(this).show(); // показываем элемент
    }).bind("ajaxComplete", function(){
        $(this).hide(); // скрываем элемент
    });
    
    $(".present_desc").hide();
    $(".present_list li").click(function(){  show_present($(this).attr('id'));    });
    $(".msg_close").click( function(){ $(this).closest('div').fadeOut().slideUp({queue:false}); $(".msg_bg").hide();} );
    
    // записываем в кукисы смещение часового пояса пользователя    
    document.cookie="time_offset=" + ( (new Date()).getTimezoneOffset()*60)*(-1);
      
    // всплывающие подсказки           
    $('a, input, label, .present_head').tooltip({
        track: true,
        delay: 0,
        showURL: false,
        showBody: " - ",
        fade: 150
    });
                  
    // добавление нового желания
    if(can_edit) {
        
        general_use();   

    };
    
    
    
});



